//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace OpenLS.Spreadsheet.UI
{
    public class BackupFile: IDisposable
    {
        private string originalFileName;
        private string backupFileName;
        private bool committed;

        public void Commit()
        {
            committed = true;
        }

        public BackupFile(string originalFileName)
        {
            if (!File.Exists(originalFileName))
                return;
            this.originalFileName = originalFileName;
            this.backupFileName = GetAvailableFileName(originalFileName);
            File.Move(originalFileName, backupFileName);
        }

        static string GetAvailableFileName(string existingFileName)
        {
            for (int i = 0; i < 100000; i++)
            {
                string s = existingFileName + "bak" + i;
                if (!File.Exists(s))
                    return s;
            }
            return null;
        }
        

        #region IDisposable Members

        public void Dispose()
        {
            if (originalFileName == null)
                return;
            if (committed)
            {
                File.Delete(backupFileName);
            }
            else
            {
                try
                {
                    File.Delete(originalFileName);
                }
                catch
                {
                }
                File.Move(backupFileName, originalFileName);
            }

        }

        #endregion
    }
}
